/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-23 10:18:00
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-23 18:55:24
 * @FilePath: \vue3_nuxt_demo\server\middleware\auth.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import jwt from 'jsonwebtoken';

/***
 * 1、获取token
 * 2、判断token，如果有token，则处理token，之后再验证token值
 */

export default defineEventHandler(
  (event) => {
    //获取token值
    let token = getHeader(event,'Authorization');

    if (token) {

      //处理token
      token = token.replace('Bearer','');

      //秘钥
      const secret = 'eifuisedfuvs';

      try {

        //验证token
        const decoded: any  = jwt.verify(token, secret);
        //传递给上下文
        event.context.auth = {
          uid: decoded?.data?.data?.uid
        };

      }
      catch (e) {
        console.log('jwt 解码错误',e);
      }
    }
  }
);